package com.syp.test.clustercacheflush.util.zkflushcache.handler;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.I0Itec.zkclient.IZkChildListener;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.syp.test.clustercacheflush.util.HexStringUtil;
import com.syp.test.clustercacheflush.util.SpringContextUtil;
import com.syp.test.clustercacheflush.util.zkflushcache.CacheFlushDispacher;
import com.syp.test.clustercacheflush.util.zkflushcache.CacheTypeEnum;
import com.syp.test.clustercacheflush.util.zkflushcache.ZkCacheSyncNotify;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class CacheSyncListener implements IZkChildListener, InitializingBean {

	private Map<CacheTypeEnum, CacheFlushDispacher> cacheManger = new HashMap<>();

	@Override
	public void handleChildChange(String parentPath, List<String> currentChilds) throws Exception {
		log.info("parentPath:{}", parentPath);
		currentChilds.forEach(current -> {
			log.info("子节点：{}", current);
			String jsonString = HexStringUtil.convert2Str(current);
			JSONObject json = JSON.parseObject(jsonString);
			ZkCacheSyncNotify zkNotify = JSON.toJavaObject(json, ZkCacheSyncNotify.class);
			cacheManger.get(zkNotify.getCacheType()).flushCache(zkNotify.getCacheKey());
		});
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		for (CacheTypeEnum cacheType : CacheTypeEnum.values()) {
			CacheFlushDispacher dispacher = SpringContextUtil.getBean(cacheType.getDispacher());
			cacheManger.put(cacheType, dispacher);
		}

	}

}